<template>
  <view class="search">
    <musicHead icon="true" iconBlack="true" title="搜索"></musicHead>
    <view class="search-search">
      <text class="iconfont icon-sousuokuang"></text>
      <input
        type="text"
        placeholder="搜索"
        v-model="keyWord"
        :focus="focusState"
        @keydown.enter="handlerHistory"
        @input="getUserInput"
      />
      <text v-if="keyWord" @tap="deleteKeyWord">x</text>
    </view>
    <view class="container">
      <scroll-view scroll-y="true">
        <block v-if="searchType == 1">
          <view class="search-history" v-if="isHistory">
            <view class="search-history-head">
              <view>历史记录</view>
              <text
                @tap="deleteHistory"
                class="iconfont icon-shanchu"
                style="{font-size: 40rpx;}"></text>
            </view>
            <view class="search-history-list">
              <view
                class="search-history-list-item"
                v-for="(item, index) in searchHistory"
                :key="index"
                @tap="getKeyWord(item)"
              >
                <view>{{ item }}</view>
              </view>
            </view>
          </view>
          <view class="search-hot">
            <view class="search-hot-head"> 热搜榜 </view>
            <view class="search-hot-list">
              <view
                class="search-hot-list-item"
                v-for="(item, index) in searchHot"
                :key="index"
                @tap="getKeyWord(item.searchWord)"
              >
                <view class="search-hot-list-item-left">{{ index + 1 }}</view>
                <view class="search-hot-list-item-center">
                  <view class="search-hot-list-item-center-top">
                    <view>{{ item.searchWord || "" }}</view>
                    <image :src="item.iconUrl || ''" mode="" />
                  </view>
                  <view class="search-hot-list-item-center-bottom">{{
                    item.content
                  }}</view>
                </view>
                <view class="search-hot-list-item-right">{{ item.score }}</view>
              </view>
            </view>
          </view>
        </block>
        <block v-if="searchType == 2">
          <view class="search-result" v-if="searchList.length != 0">
            <view
              @tap="goToDetail(item.id)"
              class="search-result-item"
              v-for="(item, index) in searchList"
              :key="index"
            >
              <view class="search-result-item-left">
                <view>{{ item.name }}</view>
                <view
                  >{{ item.artists[0].name || "" }}-{{
                    item.album.name || ""
                  }}</view
                >
              </view>
              <text
                class="search-result-item-right iconfont icon-bofang"
              ></text>
            </view>
          </view>
          <view v-else>暂无结果</view>
        </block>

        <block v-else-if="searchType == 3">
          <view class="search-suggest">
            <view class="search-suggest-title">搜索{{ keyWord }}</view>
            <view class="search-suggest-item" v-for="(item, index) in suggestList" :key="index" @tap="handleToWord(item.keyword)"> <text class="iconfont iconsearch"></text> {{ item.keyword }}</view>
          </view>
        </block>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { searchHot, searchSuggest, searchWord } from "@/api";
export default {
  data() {
    return {
      searchHot: [],
      searchHistory: [],
      searchList: [],
      suggestList: [],
      keyWord: "",
      focusState: false,
      isHistory: false,
      searchType: 1,
      timer: null,
    };
  },
  onLoad(params) {
    this.getSearchHot();
    this.focusState = true;
    const _this = this;
    // 从本地存储中获取历史搜索记录
    uni.getStorage({
      key: "searchHistory",
      success: function (res) {
        if (res.data.length > 0) {
          _this.isHistory = true;
        }
        _this.searchHistory = res.data;
      },
    });
  },
  methods: {
    async getSearchHot() {
      try {
        let data = await searchHot();
        this.searchHot = data.data || [];
        console.log(data.data);
      } catch (error) {}
    },

    getKeyWord(keyWord) {
      this.focusState = false;
      this.keyWord = keyWord;
      // 获取到焦点
      this.$nextTick(() => {
        this.focusState = true;
      });
      this.handlerHistory();
    },

    handlerHistory() {
      this.searchHistory.unshift(this.keyWord);
      this.searchHistory = [...new Set(this.searchHistory)];
      if (this.searchHistory.length > 10) {
        this.searchHistory.length = 10;
      }
      // 存储到本地存储
      uni.setStorage({
        key: "searchHistory",
        data: this.searchHistory,
      });

      this.getSearchList(this.keyWord);
    },

    // 点击下面的内容调用搜索结果
    async getSearchList(keyWord) {
      //改变调用接口搜索，改变搜索场景
      try {
        let data = await searchWord(keyWord);
        this.searchList = data.result.songs || [];

        this.$store.commit("Detail/GET_SONGLIST", this.searchList);
        this.searchType = 2;
      } catch (error) {}
    },

    deleteHistory() {
      this.searchHistory = [];
      this.isHistory = false;
      uni.removeStorage({
        key: "searchHistory",
        success: function (res) {},
      });
    },

    deleteKeyWord() {
      this.focusState = false;
      this.keyWord = "";
      this.$nextTick(() => {
        this.focusState = true;
      });
      this.searchType = 1;
    },

    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/musicDetail/index?id=${id}`,
      });
    },

    // 去搜索
    handleToWord(word) {
      this.keyWord = word;
      this.getSearchList(word);
    },

    // 获取用户输入
    getUserInput({ detail }) {
      // 输入为空返回场景1
      if (detail.value == "") {
        this.searchType = 1;
        return;
      }

      clearTimeout(this.timer);
      this.timer = null;
      if (detail.value) {
        this.timer = setTimeout(async () => {
          //获取搜索提示
          try {
            let data = await searchSuggest(detail.value);
            console.log(data);
            this.suggestList = data.result.allMatch || [];
            console.log(this.suggestList);
            this.searchType = 3;
          } catch (error) {}
        }, 100);
      }
    },
  },

  watch: {
    searchHistory() {
      if (this.searchHistory.length > 0) {
        this.isHistory = true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: calc(100vh - 147px);
  overflow: hidden;
}

.search-search {
  display: flex;
  background-color: #f7f7f7;
  height: 73rpx;
  margin: 40rpx 30rpx 30rpx 30rpx;
  border-radius: 50rpx;
  align-items: center;

  & > text {
    margin: 0 27rpx;
    font-size: 42rpx;
  }
  & > input {
    font-size: 30rpx;
    flex: 1;
  }
  & > text:nth-of-type(2) {
    margin-left: 20;
    font-size: 36rpx;
    line-height: 73rpx;
  }
}

.search-history {
  margin: 40rpx 30rpx 30rpx 30rpx;
  .search-history-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 34rpx;
  }

  .search-history-list {
    display: flex;
    flex-wrap: wrap;
    margin-top: 20rpx;
    .search-history-list-item {
      position: relative;
      margin: 20rpx 30rpx 10rpx 0rpx;
      view {
        padding: 15rpx 25rpx;
        border-radius: 99999rpx;
        background-color: #f7f7f7;
      }

      text {
        position: absolute;
        top: -18rpx;
        right: 5rpx;
      }
    }
  }
}

.search-hot {
  margin: 40rpx 30rpx 30rpx 30rpx;
  margin-top: 60rpx;
  .search-hot-head {
    font-size: 36rpx;
  }
  .search-hot-list {
    display: flex;
    flex-direction: column;
    margin-top: 20rpx;
    .search-hot-list-item {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      margin: 20rpx 0rpx;
      .search-hot-list-item-left {
        font-size: 42rpx;
        padding: 20rpx 20rpx 20rpx 0rpx;
        text-align: left;
        margin-right: 30rpx;
      }
      .search-hot-list-item-center {
        display: flex;
        flex-direction: column;
        // align-items: center;
        // justify-items: center;
        .search-hot-list-item-center-top {
          display: flex;
          align-items: center;
          view {
            font-size: 38rpx;
            margin-right: 8rpx;
          }
          image {
            width: 60rpx;
            height: 24rpx;
          }
        }
        .search-hot-list-item-center-bottom {
          display: -webkit-box; /*弹性伸缩盒子模型显示*/
          -webkit-box-orient: vertical; /*排列方式*/
          -webkit-line-clamp: 1; /*显示文本行数(这里控制多少行隐藏)*/
          overflow: hidden; /*溢出隐藏*/
          text-overflow: ellipsip; /*溢出显示省略号*/
          color: #878787;
          margin-right: 30rpx;
        }
      }
      .search-hot-list-item-right {
        margin-left: auto;
        color: #878787;
      }
    }
  }
}

.search-result {
  border-top: 1rpx solid #878787;
  display: flex;
  flex-direction: column;
  .search-result-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 30rpx;
    margin-top: 20rpx;
    padding: 30rpx 0rpx;
    border-bottom: 1rpx solid #878787;
    .search-result-item-left {
      view:nth-child(2) {
        margin-top: 10rpx;
        color: #878787;
      }
    }
    text {
      font-size: 48rpx;
      color: #878787;
    }
  }
}

.search-suggest {
  border-top: 2rpx #e5e5e5 solid;
  padding: 30rpx;
  font-size: 26rpx;
}
.search-suggest-title {
  color: #537caa;
  margin-bottom: 40rpx;
}
.search-suggest-item {
  color: #666666;
  margin-bottom: 70rpx;
}
.search-suggest-item text {
  color: #c2c2c2;
  font-size: 26rpx;
  margin-right: 26rpx;
}
</style>